const express = require('express')
const { User, Manga, UserFavorite } = require('../models')
const { authenticateToken } = require('../middleware/auth')
const router = express.Router()

// 获取用户书架
router.get('/favorites', authenticateToken, async (req, res) => {
  try {
    const favorites = await UserFavorite.findAll({
      where: { userId: req.user.userId },
      include: [{
        model: Manga,
        as: 'manga',
        include: [{
          model: require('../models/Chapter'),
          as: 'chapters',
          limit: 1,
          order: [['chapterNumber', 'DESC']]
        }]
      }],
      order: [['updatedAt', 'DESC']]
    })

    res.json({ data: favorites })
  } catch (error) {
    console.error('获取书架错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 添加到书架
router.post('/favorites/:mangaId', authenticateToken, async (req, res) => {
  try {
    const { mangaId } = req.params
    const { isFollowing = true, notifyNewChapter = true } = req.body

    const [favorite, created] = await UserFavorite.findOrCreate({
      where: {
        userId: req.user.userId,
        mangaId
      },
      defaults: {
        isFollowing,
        notifyNewChapter
      }
    })

    if (!created) {
      await favorite.update({ isFollowing, notifyNewChapter })
    }

    res.json({ 
      message: created ? '已添加到书架' : '已更新书架信息',
      data: favorite 
    })
  } catch (error) {
    console.error('添加到书架错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 从书架移除
router.delete('/favorites/:mangaId', authenticateToken, async (req, res) => {
  try {
    const { mangaId } = req.params

    const result = await UserFavorite.destroy({
      where: {
        userId: req.user.userId,
        mangaId
      }
    })

    if (result === 0) {
      return res.status(404).json({ error: '未找到收藏记录' })
    }

    res.json({ message: '已从书架移除' })
  } catch (error) {
    console.error('移除收藏错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 更新阅读进度
router.put('/favorites/:mangaId/progress', authenticateToken, async (req, res) => {
  try {
    const { mangaId } = req.params
    const { lastReadChapter, lastReadPage, readProgress } = req.body

    const favorite = await UserFavorite.findOne({
      where: {
        userId: req.user.userId,
        mangaId
      }
    })

    if (!favorite) {
      return res.status(404).json({ error: '未找到收藏记录' })
    }

    await favorite.update({
      lastReadChapter,
      lastReadPage,
      readProgress: { ...favorite.readProgress, ...readProgress }
    })

    res.json({ message: '阅读进度已更新', data: favorite })
  } catch (error) {
    console.error('更新阅读进度错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 获取用户偏好设置
router.get('/preferences', authenticateToken, async (req, res) => {
  try {
    const user = await User.findByPk(req.user.userId, {
      attributes: ['preferences']
    })

    if (!user) {
      return res.status(404).json({ error: '用户不存在' })
    }

    res.json({ data: user.preferences })
  } catch (error) {
    console.error('获取用户偏好错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

// 更新用户偏好设置
router.put('/preferences', authenticateToken, async (req, res) => {
  try {
    const user = await User.findByPk(req.user.userId)
    
    if (!user) {
      return res.status(404).json({ error: '用户不存在' })
    }

    const newPreferences = { ...user.preferences, ...req.body }
    await user.update({ preferences: newPreferences })

    res.json({ message: '偏好设置已更新', data: newPreferences })
  } catch (error) {
    console.error('更新用户偏好错误:', error)
    res.status(500).json({ error: '服务器错误' })
  }
})

module.exports = router
